package com.eascs.workflow.email.service.impl;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.notify.constant.ModelResult;
import com.eascs.notify.mail.MailNotifier;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailNotifyResponse;
import com.eascs.workflow.common.entity.sys.SysEmail;
import com.eascs.workflow.email.dao.SysSendEmailOrMessageDao;

@Service("MailService")
public class MailNotifierImpl implements MailNotifier {

	private final Logger logger = LoggerFactory.getLogger(MailNotifier.class);

	@Autowired
	private SysSendEmailOrMessageDao dao;
	
	
	/*
	 * 邮件发送的实现
	 * 必填项：
	 * param:流水号（ requestId）
	 *      请求时间戳（requestDateTime）
	 *      请求系统编码(systemCode)--业务系统代号
	 *      发送类型(mailSendType)--MailSendType发送类型
	 *      业务编码 (bizCode)--每个系统业务类型分类
	 *      邮件标题(title)
	 *      邮件内容(content)
	 * 接收人(recipientTo)、抄送人(recipientCc)、暗抄人(recipientBcc)三项目至少传入一个
	 * 
	 */
	@Override
	public ModelResult<MailNotifyResponse> notify(MailNotifyRequest mailNotifyRequest) {
		
		ModelResult<MailNotifyResponse> model = new ModelResult<MailNotifyResponse>();
		
		//校验
		ModelResult<Boolean> modelCheck=checkMail(mailNotifyRequest);
		if(!modelCheck.isSuccess()){
			return model.withError(modelCheck.getErrCode(),modelCheck.getErrMsg());
		}
		//入库
		ModelResult<Boolean> saveModel=saveMail(mailNotifyRequest);//保存数据
		if(!saveModel.isSuccess()){
			return model.withError(saveModel.getErrCode(),saveModel.getErrMsg());
		}
		MailNotifyResponse mailNotifyResponse=new MailNotifyResponse();
		mailNotifyResponse.setResponseId(mailNotifyRequest.getRequestId());
		mailNotifyResponse.setResponseDateTime(mailNotifyRequest.getRequestDateTime());
		model.setModel(mailNotifyResponse);
		
		
		return model;
		
	}

	
	
	
	private ModelResult<Boolean> checkMail(MailNotifyRequest mailNotifyRequest) {

		ModelResult<Boolean> model = new ModelResult<Boolean>();
		//非空判断
		//1.(请求流水号、请求时间戳、请求系统编码、发送类型、业务编码、邮件标题、邮件内容为必输入项目)
		if (StringUtil.isEmpty(mailNotifyRequest.getRequestId())||StringUtil.isEmpty(mailNotifyRequest.getRequestDateTime())||StringUtil.isEmpty(mailNotifyRequest.getSystemCode())||StringUtil.isEmpty(mailNotifyRequest.getMailSendType())||StringUtil.isEmpty(mailNotifyRequest.getBizCode())||StringUtil.isEmpty(mailNotifyRequest.getTitle())||StringUtil.isEmpty(mailNotifyRequest.getContent())) {
			logger.error("邮件参数不全(请求流水号:[{}],请求时间戳：[{}],请求系统编码:[{}],发送类型:[{}],业务编码：[{}],邮件标题:[{}],邮件内容:[{}])",mailNotifyRequest.getRequestId(),mailNotifyRequest.getRequestDateTime(),mailNotifyRequest.getSystemCode(),mailNotifyRequest.getMailSendType(),mailNotifyRequest.getBizCode(),mailNotifyRequest.getTitle(),mailNotifyRequest.getContent());
			return model.withError(MailErrorDic.CHECKERROR, "邮件参数不全...");
		}
		//2.接收人、抄送人、暗抄人三项目至少传入一个
		if(StringUtil.isEmpty(mailNotifyRequest.getRecipientTo())&&StringUtil.isEmpty(mailNotifyRequest.getRecipientCc())&&StringUtil.isEmpty(mailNotifyRequest.getRecipientBcc())){
			logger.error("接收人、抄送人、暗抄人三项目至少传入一个...");
			return model.withError(MailErrorDic.CHECKERROR,"邮件接收人、抄送人、暗抄人同时为空...");
		}
		//3.发件人为空时用默认发件人发送，非空时判断发件人配置信息是否完整
		if(StringUtil.isNotBlank(mailNotifyRequest.getFrom())){
		    Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
			Matcher m = p.matcher(mailNotifyRequest.getFrom());
			if(!m.matches()){
				logger.error("[{}]:邮件格式错误！！！...",mailNotifyRequest.getFrom());
				return model.withError(MailErrorDic.CHECKERROR,"邮件格式错误...");
			}
		}
		
		return model.withModel(true);
	}


	private ModelResult<Boolean> saveMail(MailNotifyRequest mailNotifyRequest) {
		ModelResult<Boolean> model = new ModelResult<Boolean>();
		SysEmail sysEmail = new SysEmail();
		sysEmail.setTitle(mailNotifyRequest.getTitle());
		sysEmail.setSender(mailNotifyRequest.getFrom());
		sysEmail.setRecipients(mailNotifyRequest.getRecipientTo());
		sysEmail.setCc(mailNotifyRequest.getRecipientCc());
		sysEmail.setContent(mailNotifyRequest.getContent());
		sysEmail.setAppendix(mailNotifyRequest.getAttachmentPath());
		sysEmail.setStatus(0);
		sysEmail.setSystemCode(mailNotifyRequest.getSystemCode());
		sysEmail.setRecipientBcc(mailNotifyRequest.getRecipientBcc());
		sysEmail.setScheduleSendDateTime(mailNotifyRequest.getScheduleSendDateTime());
		sysEmail.setMailSendType(mailNotifyRequest.getMailSendType());
		sysEmail.setBizCode(mailNotifyRequest.getBizCode());
		sysEmail.setRequestDateTime(mailNotifyRequest.getRequestDateTime());
		sysEmail.setRequestId(mailNotifyRequest.getRequestId());
		sysEmail.setCreateTime(new Date());
		int i =dao.insertEmail(sysEmail)  ;
		if(i==0){
			return model.withError(MailErrorDic.SQLERROR,"邮件数据入库异常...");
		}
		return model.withModel(true);
	}



}
